package com.shinhye.elephantsafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.TextView;

import com.shinhye.elephantsafe.R;
import com.shinhye.elephantsafe.db.dao.AddressDao;

public class ShowAddressService extends Service {

	private static final String TAG = "ShowAddressService";
	private TelephonyManager telManager;
	private MyPhoneStateListener listener;
	private OutCallRecevier recevier;
	private WindowManager wm;
	private View view;
	private SharedPreferences sp;
	private WindowManager.LayoutParams params;
	private int windowWidth;
	private int windowHeight;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	//自定义广播接收者
	private class OutCallRecevier extends BroadcastReceiver {
		private final String TAG = "OutCallRecevier";
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.w(TAG, "去电广播接收者收到去电广播！");
			String phone = getResultData();
			String address = AddressDao.addressQuery(phone);
			if(!TextUtils.isEmpty(address)) {
				//自定义吐司
				MyToast(address);
			}
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate() {
		//注册一个广播接收者
		recevier = new OutCallRecevier();
		IntentFilter intentFilter = new IntentFilter("android.intent.action.NEW_OUTGOING_CALL");
		registerReceiver(recevier, intentFilter);
		
		//打开电话监听器，监听电话�刺�
		telManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		listener = new MyPhoneStateListener();
		telManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
		
		wm = (WindowManager) getSystemService(WINDOW_SERVICE);
		windowWidth = wm.getDefaultDisplay().getWidth();
		windowHeight = wm.getDefaultDisplay().getHeight();
		
		sp = getSharedPreferences("Setting", MODE_PRIVATE);
	}
	
	/**
	 * A Toast implement for showing address while calling.
	 * @param address
	 */
	public void MyToast(String address) {
		view = View.inflate(this, R.layout.toast_address, null);
		
		TextView tv_address = (TextView) view.findViewById(R.id.tv_call_address);
		tv_address.setText(address);
		
		int which = sp.getInt("adressstyle", 3);
		//"半透明","活力橙","卫士蓝","金属灰","苹果绿"
		int[] resids = { R.drawable.call_locate_white,
				R.drawable.call_locate_orange, R.drawable.call_locate_blue,
				R.drawable.call_locate_gray, R.drawable.call_locate_green };
		view.setBackgroundResource(resids[which]);
		
		view.setOnTouchListener(new OnTouchListener() {
			private int startX;
			private int startY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch(event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startX = (int) event.getRawX();
					startY = (int) event.getRawY();
					Log.i(TAG, "2.按下：(X=" + startX + ";Y=" + startY + ")。");
					break;
				case MotionEvent.ACTION_MOVE:
					int newX = (int) event.getRawX();
					int newY = (int) event.getRawY();
					int dx = newX - startX;
					int dy = newY - startY;
					
					params.x += dx;
					params.y += dy;
					
					if(params.x < 0)
						params.x = 0;
					if(params.y < 0)
						params.y = 0;
					if(params.x > windowWidth - view.getWidth())
						params.x = windowWidth - view.getWidth();
					if(params.y > windowHeight - view.getHeight())
						params.y = windowHeight - view.getHeight();
					
					Log.i(TAG, "2.移动到：(X=" + params.x + ";Y=" + params.y + ")。");
					wm.updateViewLayout(view, params);
					startX = (int) event.getRawX();
					startY = (int) event.getRawY();
					break;
				case MotionEvent.ACTION_UP:
					Log.i(TAG, "2.离开了");
					Editor editor = sp.edit();
					editor.putInt("lastX", params.x);
					editor.putInt("lastY", params.y);
					editor.commit();
					break;
				}
				return true;
			}
		});
		
        params = new WindowManager.LayoutParams();
        //设置历史位置
        params.x = sp.getInt("lastX", 0);
        params.y = sp.getInt("lastY", 50);
        //设置为左上角为坐标原点
        params.gravity = Gravity.TOP + Gravity.LEFT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = PixelFormat.TRANSLUCENT;
        params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;

		wm.addView(view, params);
	}

	class MyPhoneStateListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch(state) {
			case TelephonyManager.CALL_STATE_RINGING:
				String address = AddressDao.addressQuery(incomingNumber);
				if(!TextUtils.isEmpty(address)) {
					//自定义吐司
					MyToast(address);
				}
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				if(view != null)
					wm.removeView(view);
				break;
			}
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		//解注册广播接收者
		unregisterReceiver(recevier);
		recevier = null;
		
		//取消监听器
		telManager.listen(listener, PhoneStateListener.LISTEN_NONE);
		listener = null;
	}

}
